package com.newland.mesdk.demo.fragment;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.module.common.iccard.ICCardSlot;
import com.newland.mtype.module.common.iccard.ICCardSlotState;
import com.newland.mtype.module.common.iccard.ICCardType;
import com.newland.mtype.util.Dump;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.event.RadioGroupChangeListener;
import com.newland.mesdk.demo.interfaceimpl.ICCardInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF IC卡模块
 */
public class ICCardFragment extends Fragment implements OnClickListener {
	private MainActivity mainActivity;
	private ICCardInterfaceImpl icCardInterfaceImpl;
	private ICCardSlot icCardSlot;
	private ICCardType icCardType;
	private Dialog iccard_dialog;
	private RadioGroupChangeListener radioGroupChangeListener;
	private Button btnPowerOn, btnTranstion, btnGetState, btnPowerOf;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_iccard, null);
		mainActivity = (MainActivity) getActivity();
		initICardView(view);
		return view;
	}

	public void initICardView(View view) {
		btnPowerOn = (Button) view.findViewById(R.id.btn_iccard_poweron);
		btnPowerOn.setOnClickListener(this);

		btnTranstion = (Button) view.findViewById(R.id.btn_iccard_transation);
		btnTranstion.setOnClickListener(this);

		btnGetState = (Button) view.findViewById(R.id.btn_iccard_state);
		btnGetState.setOnClickListener(this);

		btnPowerOf = (Button) view.findViewById(R.id.btn_iccard_powerof);
		btnPowerOf.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			if (mainActivity.processingisLocked()) {
				mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
			} else {
				mainActivity.connectDevice();
				icCardInterfaceImpl = new ICCardInterfaceImpl();
				switch (v.getId()) {
				case R.id.btn_iccard_poweron:
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showSlodPowerOnDialog();

						}
					}).start();

					break;
				case R.id.btn_iccard_transation:
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showICCardCommunicationDialog();

						}
					}).start();

					break;
				case R.id.btn_iccard_state:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									Map<ICCardSlot, ICCardSlotState> map = new HashMap<ICCardSlot, ICCardSlotState>();
									map = icCardInterfaceImpl.checkSlotsState();
									for (Map.Entry<ICCardSlot, ICCardSlotState> entry : map.entrySet()) {
										if (entry.getKey() != null)
											if (!entry.getValue().toString().equals("NO_CARD")) {
												mainActivity.showMessage("卡槽:" + entry.getKey() + "--->" + "卡:" + entry.getValue() + "\r\n", MessageTag.DATA);
											} else {
												mainActivity.showMessage("卡槽:" + entry.getKey() + "--->" + "卡:" + entry.getValue() + "\r\n", MessageTag.DATA);
											}
									}
									mainActivity.showMessage("检测结束..." + "\r\n", MessageTag.NORMAL);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("检测异常：" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							} 


						}
					}).start();

					break;
				case R.id.btn_iccard_powerof:
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showSlodPowerOffDialog();


						}
					}).start();

					break;


				default:
					break;
				}
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.NORMAL);
		}
	}

	
	// IC卡通信请求对话框
	public void showICCardCommunicationDialog() {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mainActivity);
				;
				LayoutInflater inflater = LayoutInflater.from(mainActivity);
				final View view = inflater.inflate(R.layout.dialog_iccard, null);
				radioGroupChangeListener = new RadioGroupChangeListener(view, Const.DialogView.IC_CARD_ICCardSlot_DIALOG);
				builder.setTitle("IC卡通信请求:");
				builder.setView(view);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							icCardSlot = radioGroupChangeListener.getiCCardSlot();
							String str = "0084000004";
							byte req[] = ISOUtils.hex2byte(str);
							byte back[] = icCardInterfaceImpl.call(icCardSlot, ICCardType.CPUCARD, req, 30, TimeUnit.SECONDS);
							mainActivity.showMessage("发送数据:0084000004" + "\r\n", MessageTag.NORMAL);
							mainActivity.showMessage("接收数据:" + ISOUtils.hexString(back) + "\r\n", MessageTag.NORMAL);
							mainActivity.showMessage("IC卡通信请求 成功" + "\r\n", MessageTag.NORMAL);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage("IC卡通信异常:" + e.getMessage() + "\r\n", MessageTag.NORMAL);
							mainActivity.processingUnLock();
						} 

					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						mainActivity.processingUnLock();
					}
				});
				iccard_dialog = builder.create();
				iccard_dialog.show();
				iccard_dialog.setCancelable(false);
				iccard_dialog.setCanceledOnTouchOutside(false);

			}
		});
	}

	// IC卡卡槽下电对话框
	public void showSlodPowerOffDialog() {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mainActivity);
				LayoutInflater inflater = LayoutInflater.from(mainActivity);
				final View view = inflater.inflate(R.layout.dialog_iccard, null);
				LinearLayout ic_send_data = (LinearLayout) view.findViewById(R.id.ic_send_data);
				ic_send_data.setVisibility(View.GONE);
				radioGroupChangeListener = new RadioGroupChangeListener(view, Const.DialogView.IC_CARD_ICCardSlot_DIALOG);
				builder.setTitle("IC卡下电:");
				builder.setView(view);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							icCardSlot = radioGroupChangeListener.getiCCardSlot();
							icCardInterfaceImpl.powerOff(icCardSlot, ICCardType.CPUCARD);
							mainActivity.showMessage(icCardSlot.toString() + "下电完成" + "\r\n", MessageTag.NORMAL);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage("卡槽下电异常:" + e.getMessage() + "\r\n", MessageTag.ERROR);
							mainActivity.showMessage("请检查该卡槽是否已插入IC卡" + "\r\n", MessageTag.TIP);
							mainActivity.processingUnLock();
						} 
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						iccard_dialog.dismiss();
						mainActivity.processingUnLock();
					}
				});
				iccard_dialog = builder.create();
				iccard_dialog.show();
				iccard_dialog.setCancelable(false);
				iccard_dialog.setCanceledOnTouchOutside(false);
			}
		});
	}

	// IC卡卡槽上电对话框
	public void showSlodPowerOnDialog() {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mainActivity);
				LayoutInflater inflater = LayoutInflater.from(mainActivity);
				final View view = inflater.inflate(R.layout.dialog_iccard, null);
				LinearLayout ic_send_data = (LinearLayout) view.findViewById(R.id.ic_send_data);
				ic_send_data.setVisibility(View.GONE);
				radioGroupChangeListener = new RadioGroupChangeListener(view, Const.DialogView.IC_CARD_ICCardSlot_DIALOG);
				builder.setTitle("IC卡上电:");
				builder.setView(view);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						try {
							icCardSlot = radioGroupChangeListener.getiCCardSlot();
							System.out.println("上电卡槽====" + icCardSlot);
							byte result[] = icCardInterfaceImpl.powerOn(icCardSlot, ICCardType.CPUCARD);

							mainActivity.showMessage("上电结果 :" + Dump.getHexDump(result) + "\r\n", MessageTag.TIP);
							mainActivity.showMessage("卡槽：" + icCardSlot.toString() + "上电完成" + "\r\n", MessageTag.TIP);
							mainActivity.processingUnLock();
						} catch (Exception e) {
							mainActivity.showMessage("卡槽上电异常:" + e.getMessage() + "\r\n", MessageTag.ERROR);
							mainActivity.showMessage("请检查该卡槽是否已插入IC卡" + "\r\n", MessageTag.TIP);
							mainActivity.processingUnLock();
						} 
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						iccard_dialog.dismiss();
						mainActivity.processingUnLock();
					}
				});
				iccard_dialog = builder.create();
				iccard_dialog.show();
				iccard_dialog.setCancelable(false);
				iccard_dialog.setCanceledOnTouchOutside(false);
			}
		});

	}

}
